package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
@Slf4j

public class OrderSettingServiceImpl extends ServiceImpl<OrderSettingDao,OrderSetting> implements OrderSettingService {
    @Autowired
    private OrderSettingService orderSettingService;

    @Transactional
    @Override

    public void addAll(List<OrderSetting> orderSettings) {
        for (OrderSetting orderSetting : orderSettings) {
            editNumberByDate(orderSetting.getOrderDate(), orderSetting.getNumber());
        }

    }

    @Override
    public List<OrderSetting> getOrderSettingByMonth(int year, int month) {
        String data = year + "-%" + month+"%";
        log.info("data,{}", data);
        LambdaQueryWrapper<OrderSetting> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(OrderSetting::getOrderDate, data);
        List<OrderSetting> list = orderSettingService.list(lambdaQueryWrapper);
        return list;
    }

    @Transactional
    @Override
    public void editNumberByDate(Date orderDate, int number) {
        log.info("[预约设置-根据日期编辑]date:{},number:{}", orderDate, number);
        // 判断是否已存在
        LambdaQueryWrapper<OrderSetting> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderSetting::getOrderDate, orderDate);
        OrderSetting po = orderSettingService.getOne(lambdaQueryWrapper);
        if (null != po) {

            // 存在则更新
            LambdaQueryWrapper<OrderSetting> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();

            OrderSetting byId = orderSettingService.getById(po.getId());
            byId.setNumber(number);
            lambdaQueryWrapper1.eq(OrderSetting::getId, po.getId());
            orderSettingService.update(byId, lambdaQueryWrapper1);
        } else {
            // 不存在则插入
            orderSettingService.save(new OrderSetting(orderDate, number));
        }
    }


}
